package HttpClient

import (
	"bytes"
	"io"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
)

func UPLOAD(url, fileField, filePath string, formData map[string]string, header map[string]string) (string, error) {
	// 打开本地文件
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	// 创建一个multipart writer
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)

	// 添加表单数据
	for key, value := range formData {
		err := addMultipartBody(writer, key, value)
		if err != nil {
			return "", err
		}
	}

	// 添加文件部分的form
	fw, err := writer.CreateFormFile(fileField, filepath.Base(file.Name()))
	if err != nil {
		return "", err
	}
	_, err = io.Copy(fw, file)
	if err != nil {
		return "", err
	}

	// 关闭写入，设置终止边界
	writer.Close()

	// Construct the HTTP request
	request, err := http.NewRequest("POST", url, body)
	if err != nil {
		return "", err
	}

	// 设置上下文类型
	request.Header.Set("Content-Type", writer.FormDataContentType())

	for key, value := range header {
		request.Header.Set(key, value)
	}

	// 发送请求
	respond, err := http.DefaultClient.Do(request)
	if err != nil {
		return "", err
	}
	defer respond.Body.Close()

	data, err := io.ReadAll(respond.Body)
	if err != nil {
		return "", err
	}

	return string(data), nil
}

func addMultipartBody(writer *multipart.Writer, key, value string) error {
	fw, err := writer.CreateFormField(key)
	if err != nil {
		return err
	}

	_, err = fw.Write([]byte(value))
	if err != nil {
		return err
	}

	return nil
}
